﻿// Copyright © 2011 Paul Vanukoff (pvanukoff@gmail.com)

using System;
using System.Diagnostics;
using System.IO;
using Bravura.Core.MusicLib;
using Bravura.Native.PluginBase;

namespace BravuraCmd
{
	static class Program
	{
		static void Main(string[] args)
		{
			int sr = 48000;
			IMusicEngine me = null;
			string projFile = null;
			int? start = null;
			int? end = null;

			#region Usage

			if (args.Length == 0)
			{
				Console.WriteLine("");
				Console.WriteLine("Usage:");
				Console.WriteLine("");
				Console.WriteLine("Bravura.exe \"filename.xaml\" [ -rate=<sample rate> ] [ -start=<beat number> -end=<beat number> ]");
				Console.WriteLine("");
				return;
			}

			#endregion

			try
			{
				#region Argument Parsing

				foreach (string arg in args)
				{
					if (arg.StartsWith("-"))
					{
						string[] argParts = arg.Split('=');
						string argName = argParts[0].ToLower();
						string argData = argParts[1];
						switch (argName)
						{
							case "-rate":
							{
								sr = int.Parse(argData);
								break;
							}
							case "-start":
							{
								start = int.Parse(argData);
								break;
							}
							case "-end":
							{
								end = int.Parse(argData);
								break;
							}
						}
					}
					else
					{
						projFile = arg;
					}
				}

				#endregion

				// create and init the engine
				me = new MusicEngine(new Client(), sr);
				me.Load(new FileInfo(projFile));

				DateTime dt0 = DateTime.Now;

				// render
				if (start == null || end == null)
				{
					me.Render();
				}
				else
				{
					me.Render(start.Value, end.Value);
				}

				DateTime dt1 = DateTime.Now;

				Console.WriteLine("Rendering time : {0}", dt1 - dt0);
			}
			catch (Exception ex)
			{
				#if DEBUG
				Console.WriteLine("ERROR : " + ex.ToString());
				#else
				Console.WriteLine("ERROR : " + ex.Message);
				#endif
				Console.ReadKey();
			}

			return;
		}
	}

	class Client : IMusicEngineHost
	{
		public bool ShouldContinue()
		{
			return true;
		}

		public void LogProgress(int progress, int total)
		{
			Console.WriteLine("{0} of {1}", progress, total);
		}

		public void LogMessage(IMusicEngine source, TraceLevel severity, string message)
		{
			Console.WriteLine("{0} :: {1}", severity, message);
		}
	}
}
